﻿namespace EFS.RC.Survey.Controls
{
	public partial class Question : EFS.RC.Survey.Controls.Control
	{
		private EFS.RC.CC.CH.Entities.Surveys.Question.eAnswersFlowDirection? answersFlowDirection = null;

		#region Constructors
		/// Implicit
		public Question()
		{
			InitializeComponent();

			// do not use this constructor
			ConstructorNotAllowed();
		}

		/// Explicit
		public Question(EFS.RC.CC.CH.Entities.Surveys.Question questionObj, EFS.RC.Survey.Controls.Survey survey)
		{
			// check
			EFS.Common.Verify.Reference(questionObj, "questionObj");

			// init
			InitializeComponent();

			// register events
			UtilitiesService.SurveyAnswer_GetByQuesionIDCompleted += new System.EventHandler<Utilities.SurveyAnswer_GetByQuesionIDCompletedEventArgs>(UtilitiesService_SurveyAnswer_GetByQuesionIDCompleted);

			// set
			this.QuestionObj = questionObj;
			this.SurveyObj = survey;
			this.answersFlowDirection = questionObj.AnswersFlowDirection;


		}
		#endregion

		#region Properties
		/// Property QuestionObj: Get, Set
		public EFS.RC.CC.CH.Entities.Surveys.Question QuestionObj { get; private set; }
		public EFS.RC.Survey.Controls.Survey SurveyObj { get; private set; }

		/// Property Comment: Get
		public System.String Comment
		{
			get
			{
				return EFS.Common.Functions.String.GetTrimmedString(textBoxComment.Text);
			}
		}

		/// Property IsValid: Get
		public System.Boolean IsValid
		{
			get
			{
				return true;
			}
		}
		#endregion

		#region Utilities
		/// Validate
		public System.Boolean Validate()
		{
			// reset error
			ShowError(null);

			// cicle all answer controls
			System.Boolean areAnswersValid = true;
			System.Boolean noneSelected = true;
			foreach (EFS.RC.Survey.Controls.Answer controlAnswer in stackPanelAnswers.Children)
			{
				// test selected
				if (controlAnswer.IsSelected)
				{
					noneSelected = false;
				}

				// validate child control
				if (!controlAnswer.Validate())
				{
					areAnswersValid = false;
				}
			}

			// test answer validity
			if (!areAnswersValid)
			{
				ShowError("Invalid data");
				return false;
			}

			// test selected
			if (noneSelected)
			{
				ShowError("Please select the answer.");
				return false;
			}

			// ok
			return true;
		}

		/// Show error
		private void ShowError(System.String err)
		{
			// prepare err
			System.String errTemp = EFS.Common.Functions.String.GetTrimmedString(err);
			textBlockValidationError.Text = errTemp;
			dockPanelValidation.Visibility = EFS.Common.Verify.String(textBlockValidationError.Text) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
		}
		#endregion

		#region LoadData
		/// Load question
		private void LoadQuestion()
		{
			// set text
			textBlockQuestion.Text = QuestionObj.Text;

			if (SurveyObj.SurveySessionObj != null)
			{
				foreach (EFS.RC.CC.CH.Entities.Surveys.Sessions.AnswerInfo answer in SurveyObj.Answers)
				{
					if (QuestionObj.ID== answer.QuestionId)
					{
						textBoxComment.Text = answer.Answer.Comment;
					}
				}

				if (SurveyObj.SurveySessionObj.ReadOnly == true)
				{
					textBoxComment.IsReadOnly = true;
				}
			}

			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.InProgress(this, "Loading Answers for Question {0}", QuestionObj.ID.Value);

			// call ws
			UtilitiesService.SurveyAnswer_GetByQuesionIDAsync(QuestionObj.ID.Value);
		}

		/// LoadAnswers
		private void LoadAnswers(EFS.RC.CC.CH.Entities.Surveys.Answer[] answers)
		{
			// check
			EFS.Common.Verify.Reference(answers, "answers");

			// make controls
			for (System.Int32 i = 0; i < answers.Length; ++i)
			{
				if (i > 0)
				{
					SleepBetweenRepetitiveAsyncCalls();
				}

				EFS.RC.Survey.Controls.Answer controlAnswer = new EFS.RC.Survey.Controls.Answer(answers[i], SurveyObj.SurveySessionObj, SurveyObj.Answers);
				controlAnswer.Name = System.String.Format("controlAnswer_{0}", answers[i].ID.Value);
				controlAnswer.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
				controlAnswer.VerticalAlignment = System.Windows.VerticalAlignment.Top;
				if (i > 0)
				{
					if (stackPanelAnswers.Orientation == System.Windows.Controls.Orientation.Horizontal)
					{
						controlAnswer.Margin = new System.Windows.Thickness(20, 0, 0, 0);
					}
					else
					{
						controlAnswer.Margin = new System.Windows.Thickness(0, 5, 0, 0);
					}
				}
				stackPanelAnswers.Children.Add(controlAnswer);
				controlAnswer.radioButton.Checked += new System.Windows.RoutedEventHandler(radioButton_Checked);
			}
		}
		#endregion

		public void radioButton_Checked(object sender, System.Windows.RoutedEventArgs e)
		{
			// calling calculate function from Survey to calculate the average score for each answered question in survey
			SurveyObj.Calculate_AnswerClick();
		}

		#region WS Callbacks
		/// SurveyAnswer_GetByQuesionIDCompleted
		private void UtilitiesService_SurveyAnswer_GetByQuesionIDCompleted(object sender, Utilities.SurveyAnswer_GetByQuesionIDCompletedEventArgs e)
		{
			// close wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.Completed(this);

			try
			{
				// verify
				if (null != e.Error)
				{
					throw e.Error;
				}

				// deserialize
				EFS.RC.CC.CH.Entities.Surveys.Answer[] answers =
					EFS.Common.Serialization.Functions.Deserialize<EFS.RC.CC.CH.Entities.Surveys.Answer[]>(e.Result.ToString());

				// show
				LoadAnswers(answers);
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to retrieve answers.", ex);
			}
		}
		#endregion

		#region Events

		/// LOaded
		private void ControlQuestion_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			// no error
			ShowError(null);

			// answers flow direction
			switch (EFS.Common.Functions.Nullable<EFS.RC.CC.CH.Entities.Surveys.Question.eAnswersFlowDirection>.GetSafe(this.answersFlowDirection, EFS.RC.CC.CH.Entities.Surveys.Question.eAnswersFlowDirection.Vertical))
			{
				case EFS.RC.CC.CH.Entities.Surveys.Question.eAnswersFlowDirection.Vertical:
				{
					stackPanelAnswers.Orientation = System.Windows.Controls.Orientation.Vertical;
					break;
				}
				default:
				{
					stackPanelAnswers.Orientation = System.Windows.Controls.Orientation.Horizontal;
					break;
				}
			}

			// load question
			LoadQuestion();
		}
		#endregion
	}

}